#include "tcpServer.hpp"
#include "Protocol.hpp"
#include <memory>

using namespace std;
using namespace Server;
static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}

// req:处理好的一个完整的请求对象
// resp：根据req，进行业务处理，填充resp，
// 不用管任何读取和写入，序列化和反序列化等
bool cal(const Request &req, Response &resp)
{
    // req已经结构化完成，可以使用
    resp.exitcode_ = OK;
    resp.result_ = OK;

    switch (req.op_)
    {
    case '+':
        resp.result_=req.x_+req.y_;
        break;
    case '-':
        resp.result_=req.x_-req.y_;
        break;
    case '*':
        resp.result_=req.x_*req.y_;
        break;
    case '/':
        {
            if(req.y_!=0)
                resp.result_=req.x_/req.y_;
            else
                resp.exitcode_=DIV_ZERO;    
        }
        break;
    case '%':
        {
            if(req.y_!=0)
                resp.result_=req.x_%req.y_;
            else
                resp.exitcode_=MOD_ZERO;    
        }
        break;    
    default:
        resp.exitcode_=OP_ERROR;
        break;
    }
    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t serverport = atoi(argv[1]);
    unique_ptr<tcpServer> tsvr(new tcpServer(serverport));

    tsvr->InitServer();

    tsvr->start(cal);

    return 0;
}